package servlet;

import bean.Admin;
import dao.AdminDao;
import util.JsonWrapper;
import util.ResponseUtil;
import util.TokenUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dqy
 */
public class AdminLoginServlet extends HttpServlet {
    private AdminDao adminDao = new AdminDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //		获取用户名密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Admin admin = new Admin(username, password);  //查询条件
        JsonWrapper result = new JsonWrapper();

        try {
            admin = adminDao.login(admin);
            if (admin != null) {
                result.setStatus(200);
                result.setMsg("success");
                result.setDataEntry("token", TokenUtil.generateJWT(username + req.getRemoteHost()));
                result.setDataJsonObject("haveMessage", adminDao.haveMessage(admin));
                result.setDataObject("admin", admin);
            } else {
//				查询正确，骑行用户信息验证失败
                result.setStatus(404);  //待定
                result.setMsg("failed");
            }
        } catch (Exception e) {
            result.setStatus(301);  //待定
            result.setMsg("failed");
        }
        ResponseUtil.write(resp, result.get());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ResponseUtil.writeBadRequest(resp);
    }
}
